package com.yuwen.yuwenRPC.loadbalancer;

import com.yuwen.yuwenRPC.model.ServiceMetaInfo;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassNameRoundRobinLoadBalancer
 * @Description TODO
 * @Author钰玟
 * @Date2025/4/5 下午8:18
 * @Version 1.0
 **/


/**
 * 轮询负载均衡器（）
 */
public class RoundRobinLoadBalancer implements LoadBalancer {

    private final AtomicInteger currentIndex = new AtomicInteger(0);

    @Override
    public ServiceMetaInfo select(Map<String, Object> requestParams, List<ServiceMetaInfo> servicesMetaInfoList) {
        //判断列表是否为空
        if(servicesMetaInfoList.isEmpty()){
            return null;
        }
        //如果只有一个服务，则无需轮询
        int size = servicesMetaInfoList.size();
        if(size==1){
            return servicesMetaInfoList.get(0);
        }
        //进行轮询算法  取模算法
        int index = currentIndex.getAndIncrement() % size;
        return servicesMetaInfoList.get(index);
    }
}
